package zhaomh.zlogin.Listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.player.*;
import zhaomh.zlogin.Commands.LoginCommand;
import zhaomh.zlogin.Data;
import zhaomh.zlogin.PlayerData;

import java.util.Arrays;
import java.util.List;

public class Listeners implements Listener {
    @EventHandler
    public boolean playerCommandPreprocessEvent(PlayerCommandPreprocessEvent e) {
        String message = e.getMessage();
        System.out.println(message + " << message");
        List<String> list = Data.config.getStringList("commands.login");
        for (int i = 0; i < list.size(); i++) {
            list.set(i,"/" + list.get(i));
        }
        System.out.println(list + " << list-login");
        String[] s = message.split(" ");
        if (list.contains(s[0])) {
            System.out.println(s + " << s-login");
            if (s.length > 1) {
                e.setMessage("/login " + s[1]);
                return true;
            }else {
                e.setMessage("/login");
                return true;
            }
        }
        list = Data.config.getStringList("commands.register");
        for (int i = 0; i < list.size(); i++) {
            list.set(i,"/" + list.get(i));
        }
        System.out.println(list + " << list-login");
        s = message.split(" ");
        if (list.contains(s[0])) {
            System.out.println(s + " << s-register");
            if (s.length > 1) {
                e.setMessage("/register " + s[1]);
                return true;
            }else {
                e.setMessage("/register");
                return true;
            }
        }

        boolean b = !PlayerData.isPlayerInList(e.getPlayer());
        if (b)
            e.setCancelled(true);
        return b;
    }
    @EventHandler
    public boolean join(PlayerJoinEvent e) {
        PlayerData.joinPlayer(e.getPlayer());
        return true;
    }
    //当玩家退出服务器时触发这个事件.
    @EventHandler
    public boolean quit(PlayerQuitEvent e) {
        System.out.println(e.getPlayer());
        LoginCommand.removePlayerInMap(e.getPlayer().getName());
        PlayerData.removePlayer(e.getPlayer());
        return true;
    }
    //当玩家聊天时触发这个事件.
    @EventHandler
    public boolean chat(AsyncPlayerChatEvent e) {
        boolean b = !PlayerData.isPlayerInList(e.getPlayer());
        if (b)
            e.setCancelled(true);
        return b;
    }
    //玩家移动事件.
    @EventHandler
    public boolean move(PlayerMoveEvent e) {
        boolean b = !PlayerData.isPlayerInList(e.getPlayer());
        if (b)
            e.setCancelled(true);
        return b;
    }
    //当玩家对一个对象或空气进行交互时触发本事件.
    @EventHandler
    public boolean playerInteractEvent(PlayerInteractEvent e) {
        boolean b = !PlayerData.isPlayerInList(e.getPlayer());
        if (b)
            e.setCancelled(true);
        return b;
    }
}
